﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.XPath;
using System.Xml;

namespace InfoPathDebugger.RuleManager
{
    /// <summary>
    /// This executor is used to execute assignment action.
    /// </summary>
    public class AssignmentActionExecutor : IActionExecutor
    {
        #region IActionExecutor Members

        public void Execute(XPathNavigator actionNav, XPathNavigator dataSourceNav, Object additionalData)
        {
            // Currently, this executor just support the simple scenario, which is far from the full functionality of assignment action in InfoPath.
            String targetFieldXPath = actionNav.GetAttribute("targetField", String.Empty);
            String value = parseExpression(actionNav.GetAttribute("expression", String.Empty));

            if (!XPathHelper.SetNodeValue(dataSourceNav, "//" + targetFieldXPath, value, "my"))
            {
                throw new ApplicationException(String.Format("Failed to set value '{0}' to '{1}'", value, targetFieldXPath));
            }
        }

        private String parseExpression(String expression)
        {
            expression = expression.Replace("\"", "").Trim();
            
            if (expression == "xdUser:get-UserName()")
            {
                expression = String.Format("{0}\\{1}", Environment.UserDomainName, Environment.UserName);
            }

            return expression;
        }

        #endregion
    }
}
